<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>登录日志</span>
      </div>
      <!-- 搜索表单 -->
      <el-form
        :model="where"
        class="ele-form-search"
        label-width="75px"
        @keyup.enter.native="reload"
        @submit.native.prevent>
        <div class="app-container">
          <div class="filter-container">
            <el-input
              v-model="where.username"
              clearable
              placeholder="用户账户"
              style="width: 200px; margin-right: 6px;"
              @clear="reload"/>

            <el-date-picker
              v-model="daterange"
              :clearable="false"
              :picker-options="pickerOptions"
              end-placeholder="登录时间结束日期"
              range-separator="-"
              start-placeholder="登录时间开始日期"
              style="width: 350px; margin-right: 6px;"
              type="datetimerange"
              unlink-panels
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="onDateRangeChoose"/>

            <el-button

              icon="el-icon-search"
              style="margin-right: 6px;"
              type="primary"
              @click="reload">搜索
            </el-button>

            <el-button icon="el-icon-refresh" style="margin-left: 2px;" @click="reset">重置
            </el-button>

          </div>
        </div>
      </el-form>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="url"
        :max-height="defaultHeight"
        :where="where">
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-button
            v-if="$hasPermission('login-record:export')"

            icon="el-icon-download"
            size="small"
            type="primary"
            @click="exportData">导出日志
          </el-button>
          <el-button
            v-if="$hasPermission('login-record:delete')"
            :loading="loading"

            icon="el-icon-download"
            size="small"
            type="danger"
            @click="deleteData"
          >删除三个月之前日志
          </el-button>
        </template>
        <!-- 操作类型列 -->
        <template slot="operType" slot-scope="{row}">
          <el-tag
            :type="['success','danger','info','warning'][row.operType]"
            size="mini">
            {{ ['登录成功', '登录失败', '退出登录', '刷新TOKEN'][row.operType] }}
          </el-tag>
        </template>
      </ele-pro-table>
    </el-card>
  </div>
</template>

<script>
import XLSX from 'xlsx';

export default {
  name: 'SystemLoginRecord',
  data() {
    return {
      // 表格高度
      defaultHeight: 0,
      // 删除按钮loading
      loading: false,
      // 表格数据接口
      url: '/log/loginRecord',
      // 表格列配置
      columns: [
        {
          columnKey: 'index',
          type: 'index',
          width: 45,
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'user',
          label: '账户',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'nickname',
          label: '用户名',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'device',
          label: '操作系统',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'browser',
          label: '浏览器',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'operType',
          label: '操作类型',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110,
          slot: 'operType'
        },
        {
          prop: 'ip',
          label: '登录IP',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'addr',
          label: '登录地区',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'time',
          label: '登录时间',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110,
          formatter: (row, column, cellValue) => {
            return this.$util.toDateString(cellValue);
          }
        }
      ],
      // 表格搜索条件
      where: {},
      // 筛选日期范围
      daterange: null,
      // 日期时间选择器快捷项
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime());
              start = start.getFullYear() + "-" + (start.getMonth() + 1) + "-" + start.getDate() + ' 00:00:00';
              let end = new Date();
              end.setTime(end.getTime() + 24 * 60 * 60 * 1000);
              end = end.getFullYear() + "-" + (end.getMonth() + 1) + "-" + end.getDate() + ' 00:00:00';
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 24 * 60 * 60 * 1000);
              start = start.getFullYear() + "-" + (start.getMonth() + 1) + "-" + start.getDate() + ' 00:00:00';
              let end = new Date();
              end.setTime(end.getTime());
              end = end.getFullYear() + "-" + (end.getMonth() + 1) + "-" + end.getDate() + ' 00:00:00';
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - (7 * (24 * 60 * 60 * 1000)));
              start = start.getFullYear() + "-" + (start.getMonth() + 1) + "-" + start.getDate() + ' 00:00:00';
              let end = new Date();
              end.setTime(end.getTime());
              end = end.getFullYear() + "-" + (end.getMonth() + 1) + "-" + end.getDate() + ' 00:00:00';
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近半月',
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - (15 * (24 * 60 * 60 * 1000)));
              start = start.getFullYear() + "-" + (start.getMonth() + 1) + "-" + start.getDate() + ' 00:00:00';
              let end = new Date();
              end.setTime(end.getTime());
              end = end.getFullYear() + "-" + (end.getMonth() + 1) + "-" + end.getDate() + ' 00:00:00';
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - (30 * (24 * 60 * 60 * 1000)));
              start = start.getFullYear() + "-" + (start.getMonth() + 1) + "-" + start.getDate() + ' 00:00:00';
              let end = new Date();
              end.setTime(end.getTime());
              end = end.getFullYear() + "-" + (end.getMonth() + 1) + "-" + end.getDate() + ' 00:00:00';
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - (90 * (24 * 60 * 60 * 1000)));
              start = start.getFullYear() + "-" + (start.getMonth() + 1) + "-" + start.getDate() + ' 00:00:00';
              let end = new Date();
              end.setTime(end.getTime());
              end = end.getFullYear() + "-" + (end.getMonth() + 1) + "-" + end.getDate() + ' 00:00:00';
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近半年',
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - (180 * (24 * 60 * 60 * 1000)));
              start = start.getFullYear() + "-" + (start.getMonth() + 1) + "-" + start.getDate() + ' 00:00:00';
              let end = new Date();
              end.setTime(end.getTime());
              end = end.getFullYear() + "-" + (end.getMonth() + 1) + "-" + end.getDate() + ' 00:00:00';
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - (365 * (24 * 60 * 60 * 1000)));
              start = start.getFullYear() + "-" + (start.getMonth() + 1) + "-" + start.getDate() + ' 00:00:00';
              let end = new Date();
              end.setTime(end.getTime());
              end = end.getFullYear() + "-" + (end.getMonth() + 1) + "-" + end.getDate() + ' 00:00:00';
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      }
    };
  },
  created() {
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
  },

  methods: {
    /*设置表格高度*/
    getHeight() {
      this.defaultHeight = window.innerHeight - 360;
    },

    /* 刷新表格 */
    reload(isPage) {
      let obj = {where: this.where};
      if (!isPage) {
        obj.page = 1;
      }
      this.$refs.table.reload(obj);
    },

    /* 重置搜索 */
    reset() {
      for (let key in this.where) {
        this.where[key] = null;
      }
      this.daterange = null;
      this.reload();
    },
    /* 日期选择改变回调 */
    onDateRangeChoose() {
      if (this.daterange && this.daterange.length === 2) {
        this.where.createTimeStart = this.daterange[0];
        this.where.createTimeEnd = this.daterange[1];
      } else {
        this.where.createTimeStart = null;
        this.where.createTimeEnd = null;
      }
    },
    /* 删除日志 */
    deleteData() {
      this.$confirm('该操作不可恢复, 确定是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        this.$http.delete('/log/loginRecord').then(res => {
          this.loading = false;
          if (res.data.code === 0) {
            this.$message({type: 'success', message: res.data.msg});
            this.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          this.loading = false;
          this.$message.error(e.message);
        });
      });
    },
    /* 导出数据 */
    exportData() {
      let where = this.where;
      where.page = this.$refs.table.page;
      where.limit = this.$refs.table.limit;
      let array = [['账户', '用户名', '操作系统', '浏览器', '操作类型', '登录IP', '登录地区', '登录时间']];
      const loading = this.$loading({lock: true});
      this.$http.post('/log/loginRecord', where).then(res => {
        loading.close();
        if (res.data.code === 0) {
          res.data.data.forEach(d => {
            array.push([
              d.user,
              d.nickname,
              d.device,
              d.browser,
              ['登录成功', '登录失败', '退出登录', '刷新TOKEN'][d.operType],
              d.ip,
              d.addr,
              d.time,
              this.$util.toDateString(d.createTime)
            ]);
          });
          this.$util.exportSheet(XLSX, array, '登录日志');
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        loading.close();
        this.$message.error(e.message);
      });
    }
  }
}
</script>

<style scoped>

</style>
